<?php

namespace app\common\model;

use app\common\model\marketing\MarketingCoupons;
use think\Cache;
use think\Db;
use think\Model;
use traits\model\SoftDelete;


class Scenic extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    //表名
    protected $name = 'scenic';
    protected $shop_id = null; 

    /**
     * @param $value
     * 设置shop_id
     */
    public function setShopId($value)
    {
        $this->shop_id = $value;
    }


    /**
     * [scenicInfo 商家须知]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-24
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    public function scenicInfo($scenic_id)
    {
        $scenic = $this->where('id', $scenic_id)->find();
        $data = [
            [
                'title' => '景区名称',
                'value' => $scenic['scenic_name'],
            ],
            [
                'title' => '景区标签',
                'value' => Category::getScenicLabel($scenic->sceniclabel),
            ],
            [
                'title' => '所在地区',
                'value' => $scenic['city'],
            ],
            [
                'title' => '具体地址',
                'value' => $scenic['address'],
            ],
            [
                'title' => '联系电话',
                'value' => $scenic['scenic_tel'],
            ],
            [
                'title' => '景区图片',
                'value' => explode(',', $scenic['scenic_images']),
            ],
            [
                'title' => '景区须知',
                'value' => replacePicUrl($scenic['scenic_notice'], request()->root(true)),
            ],
            [
                'title' => '景区详情',
                'value' => replacePicUrl($scenic['details'], request()->root(true)),
            ],
        ];

        return $data;
    }


    /**
     * [getMinPrice 最低的销售价]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    [type]      $goods_id [description]
     * @return   [type]                [description]
     */
    public function getMinPrice($scenic_id)
    {

        $minPrice = Sales::where(['scenic_id' => $scenic_id,'sales_status' => 1])->min('salePrice');
        return $minPrice;
    }



    /**
     * [mark 评分]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    public function mark($scenic_id)
    {

        $score = $this->where('id', $scenic_id)->value('score');
        return $score;
    }
    /**
     * [sold 已售]
     * @Author   ZhouYunpeng
     * @DateTime 2022-02-22
     * @param    [type]      $scenic_id [description]
     * @param    [type]                 [description]
     */
    public function sold($scenic_id)
    {
        $total_sales = $this->where('id', $scenic_id)->value('total_sales');
        return $total_sales;
    }



    /**
     * [getDistributorScenic 分销商商品所在景区id]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-18
     * @param    [type]      $user_id [description]
     * @return   [type]               [description]
     */
    public function getDistributorScenic($user_id)
    {
        $user = Db::name('user')->field('store_id')->find($user_id);
        $list = Db::name('goods')
                ->alias('g')
                ->where(['g.store_id'=>$user['store_id'],'s.status'=>1,'s.delete_time'=>null,'d.unified'=>['neq','not null']])
                ->join('distribution_allocation d','d.goods_id = g.id','LEFT')
                ->join('scenic s','s.id = g.scenic_id','LEFT')
                ->field('s.id')
                ->group('s.id')
                ->select();
        $list = array_column($list, 'id');
        return $list;
    }


    /**
     * [getPicture 获取景区图片]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-15
     * @return   [type]      [description]
     */
    public function getPicture($scenic_id)
    {

        $pic = $this->where('id', $scenic_id)->value('scenic_images');
        $image = explode(',', $pic);
        return reset($image);
        
    }


    /**
     * [getPicture 获取全部景区图片]
     * @Author   zhangxiaohei
     * @DateTime 2023-02-26
     * @return   [type]      [description]
     */
    public function getPictures($scenic_id)
    {

        $pic = $this->where('id', $scenic_id)->value('scenic_images');
        $image = explode(',', $pic);
        return $image;
        
    }


    /**
     * [getScenicList 获取景区列表]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-18
     * @param    array       $where [description]
     * @return   [type]             [description]
     */
    public function getScenicList($where = [], $field = ['id'], $page = 1, $order = 'weigh desc',$limit=10)
    {

        $list = $this->where($where)->field($field)->order($order)->page($page, $limit)->select();
        if (!$list) {
            return [];
        }
       
        $goodsModel = new Goods();
        $list = collection($list)->toArray();
        foreach ($list as &$scenic) {
            // $goods_id = $goodsModel->getGoodsIdList($this->shop_id,$scenic['id']);
            $scenic_images          = explode(',', $scenic['scenic_images']);
            $scenic['scenic_image'] = current($scenic_images);
            $scenic['minPrice']     = $this->getMinPrice($scenic['id']);
            $scenic['mark']         = $scenic['score'];
            $scenic['tag']          = (new Goods())->tag($scenic['id'], false);
            $scenic['coupons']      = MarketingCoupons::getUsersBusinessIdsReceiveCoupons($scenic['id']);
        }
        return $list;
    }
    
    


    /**
     * [getScenicListCount 获取景区列表,包含分页和总数]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-18
     * @param    array       $where [description]
     * @return   [type]             [description]
     */
    public function getScenicListCount($where = [], $field = ['id'], $page = 1, $order = 'weigh desc',$limit=10)
    {
        //$list = $this->where($where)->field($field)->order($order)->page($page, $limit)->select();
        $list = $this->where($where)->field($field)->order($order)->paginate($limit, false, ["page" => $page]);
        // var_dump(Db::getLastSql());exit();
        if (!$list) {
            return [];
        }
        $goodsModel = new Goods();
        //$list = collection($list)->toArray();
        foreach ($list as &$scenic) {
            //print_r($scenic);
            // $goods_id = $goodsModel->getGoodsIdList($this->shop_id,$scenic['id']);
            $scenic_images          = explode(',', $scenic->scenic_images);
            $scenic['scenic_image'] = current($scenic_images);
            $scenic['minPrice']     = $this->getMinPrice($scenic->id);
            $scenic['mark']         = $scenic->id;
            $scenic['tag']          = (new Goods())->tag($scenic->id, false);
        }
        return $list;
    }

    /**
     * [hotScenic 热搜]
     * @Author   ZhouYunpeng
     * @DateTime 2021-05-29
     * @param    [type]      $field [description]
     * @return   [type]             [description]
     */
    public function hotScenic($field)
    {
      $list = $this->field($field)->where(['hot_search'=>1])->page(1, 10)->select(); 
      return $list;
    }


    /**
     * [getScenic 获取商家信息]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-23
     * @param    [type]      $scenic_id [description]
     * @return   [type]                 [description]
     */
    public  function getScenic($scenic_id)
    {
        $field = [
            'id',
            'scenic_name',
            'sceniclabel',
            'category_id',
            'scenic_cat_id',
            'city',
            'address',
            'scenic_tel',
            'scenic_notice',
            'scenic_images',
            'wechat_title',
            'wechat_picture',
            'score',
            'details',
            'open_time',
            'latitude',
            'longitude',
            'total_sales',
            'message_switch',
            'with_scenic',
            'video',
            'show_details',
            'goods_details'
            ];
        $scenic = $this->field($field)->find($scenic_id);
        if (!$scenic) {
            return [];
        }
        $scenic['scenic_images'] = explode(',', $scenic['scenic_images']);
        $scenic['scenic_image']  = current($scenic['scenic_images']);
        //标签字符串
        $scenic['sceniclabel'] = Category::getScenicLabel($scenic['sceniclabel']);
        //景区评分
        $scenic['mark'] = $this->mark($scenic['id']);
        $scenic['details'] = replacePicUrl($scenic['details'], request()->root(true)); //景区详情
        return $scenic->toArray();
    }

    public function getRoute($scenic_id)
    { 
      $where = ['id' =>['in',$scenic_id]];
      $field = ['id', 'scenic_name', 'scenic_notice', 'scenic_images', 'score','category_id'];
      $list  = $this->getScenicList($where,$field);
      return $list;
    }
    
    /**
     * [getCity description]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @return   [type]      [description]
     */
    public static function getCity()
    {
        $city_list = (new static)->column('city_id');
        $city_list = array_unique($city_list);
        $list      = Db::name("region")->where('id', 'in', $city_list)->field('id,name')->select();
    
        return $list;
    }

    /**
     * [getScenicGoods 获取景区产品]
     * @Author   ZhouYunpeng
     * @DateTime 2022-03-26
     * @param    [type]      [description]
     */
    public function getScenicGoods($scenic_id)
    {
        $goodsModel = new Goods();
        $field =[
            'g.id',
            'goods_name',
            'goods_type_id',
            'total_sales',
            'before',
            'beforeHour',
            'beforeMinute',
            'beforeDay',
            'beforeTime',
            'refundRules',
            'is_virtual_sales',
            'virtual_sales',
            'is_custom',
            'tags',
            'putaway',
            'goods_status',
            'deadlineType',
            'valid_period_start',
            'unShelve',
            'total_sales'
        ];
        $goods = $goodsModel
                 ->alias('g')
                 ->join('distributor_goods d', 'd.goods_id = g.id', 'left') 
                 ->where(['goods_status' => 1,'g.scenic_id'=>$scenic_id])
                 ->field($field)
                 ->limit(2)
                 ->order('weigh desc')
                 ->select();
        foreach ($goods as &$value)
        {
          $goods_sales  = Sales::where(['goods_id' => $value['id'], 'sales_status' => 1])->find(); 
          $value['retailPrice'] = $goods_sales['retailPrice'];
          $value['salePrice']   = $goods_sales['salePrice'];
          $value['before']      = $this->getBeforeText($value);
          $value['tag']         = $goodsModel->tag($value['id'],true);
        }

        return $goods;

    }


    private function getBeforeText($goods)
    {

        if ($goods['deadlineType'] == 2 && $goods['valid_period_start'] > time()) {
                $value = '限时抢购';
        }else{
            if ($goods['before'] == 0) {
                $value = '随买随用';
            } elseif ($goods['before'] == 1) {
                $value = '用户需出行前' . $goods['beforeHour'] . '小时'. $goods['beforeMinute'] .'分钟购买';
            } elseif ($goods['before'] == 2) {
                if ($goods['beforeDay'] == 0) {
                     $value = '用户需出行当日' . date("H:i", $goods['beforeTime']) . '前下单';
                }else{
                     $value = '用户需出行前' . $goods['beforeDay'] . '天的' . date("H:i", $goods['beforeTime']) . '前下单';
                }
            }

        }

        return $value;
    }
}
